﻿using System;
using System.Linq;
using System.Reflection;
using ClosedXML.Excel;
using SuppKids.Core.Reporting.Data;

namespace SuppKids.Core.Reporting.Excel
{
	public class NormaPitaniyaReportGenerator : ExcelReportGenerator
	{
		protected override void CreateWorkbook(out XLWorkbook workbook, out IXLWorksheet worksheet)
		{
			workbook = new XLWorkbook(Assembly.GetExecutingAssembly().GetManifestResourceStream("SuppKids.Core.Reporting.Excel.Templates.NormaPitaniyaTemplate.xlsx"));
			worksheet = workbook.Worksheets.FirstOrDefault() ?? workbook.Worksheets.Add(workbook.Worksheets.Count.ToString(this.FormatProvider));
		}

		protected override void CreateContent(IXLWorksheet worksheet, IReportData reportData)
		{
			var data = reportData as NormaPitaniyaReportData;
			if (data == null)
			{
				throw new InvalidOperationException("Report data is not valid for this kind of report.");
			}

			var index = 3;
			foreach (var product in data.Products)
			{
				worksheet.Cell("A" + index).Value = product.Name;
				worksheet.Cell("B" + index).Value = product.DailyRate;
				worksheet.Cell("M" + index).FormulaR1C1 = string.Format("=SUM(C{0}:L{0})", index);
				worksheet.Cell("X" + index).FormulaR1C1 = string.Format("=SUM(N{0}:W{0})", index);
				worksheet.Cell("AI" + index).FormulaR1C1 = string.Format("=SUM(Y{0}:AH{0})", index);

				worksheet.Cell("AJ" + index).FormulaR1C1 = string.Format("=M{0}+X{0}+AI{0}", index);
                worksheet.Cell("AJ" + index).FormulaR1C1 = string.Format("=AJ{0}/30", index);
				worksheet.Cell("AL" + index).FormulaR1C1 = string.Format("=AK{0}/B{0}*100", index);
       
				index++;
			}

			var range = worksheet.Range(string.Format("A2:AL{0}", index-1));
			range.Style.Border.InsideBorder = XLBorderStyleValues.Thin;
			range.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
		}
	}
}